﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
//using System.Linq;
using System.Text;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using DBSourceToolsLib;
using DBConnectionLib;
using DBSourceToolsLib.SysObjects;
using Fireball.Windows.Forms;
using Fireball.Syntax;
using Fireball.CodeEditor.SyntaxFiles;
using System.IO;

namespace DBSourceTools
{
    public partial class DatabaseForm : MainPanelForm
    {
        private bool m_IsDeploymentTarget;
        private DatabaseEx m_Database;
        private DatabaseEx m_DeploymentDatabase;
        private DBSourceToolsLib.SysObjects.UI.Forms.DatabasePropertiesUC dbPropUC;
        CodeEditorControl m_codeEditCreate;
        CodeEditorControl m_codeEditDrop;
        //private BatchRunner m_BatchRunner;
        private string m_TempOutputFileName;
        
        

        public DatabaseForm(string strDatabase, string strType, string strObject)
            : base( strDatabase, strType, strObject)
        {
            InitializeComponent();
            this.m_Database = UserSettings.Instance().getSourceDatabase(this.m_DatabaseName);
            
        }

        private void DatabaseForm_Load(object sender, EventArgs e)
        {
            
            if (this.m_ObjectType.CompareTo("Database") == 0)
            {
                // this is a main database
                this.Icon = DBSourceTools.Properties.Resources.DBIcon_db_normal;
                this.m_IsDeploymentTarget = false;
                this.m_PropertiesSplitContainer.Panel1Collapsed = false;
                this.m_PropertiesSplitContainer.Panel2Collapsed = true;
                //this.m_propertyGrid.Visible = false;
                this.m_toolStripButtonDelete.Visible = false;
                this.m_toolStripButtonSave.Visible = true;

                dbPropUC = new DBSourceToolsLib.SysObjects.UI.Forms.DatabasePropertiesUC(this.m_Database, false);
                SourceDatabase oSource = UserSettings.Instance().getSourceDatabase(this.m_Database.NickName);
                dbPropUC.SetSourceDatabase(oSource);

                this.m_PropertiesSplitContainer.Panel1.Controls.Add(dbPropUC);
                this.m_toolStripButtonDeployTarget.Enabled = false;
                this.m_toolStripButtonDeployTarget.Visible = false;
                //this.tabControl1.TabPages.Remove(m_tabPageCreateScript);
                //this.tabControl1.TabPages.Remove(m_tabPageDropScript);
                this.TabText = this.m_Database.NickName;
                toolStripButtonCreateZip.Visible = false;
            }
            else
            {
                this.m_IsDeploymentTarget = true;
                this.Icon = DBSourceTools.Properties.Resources.DBIcon_targets_blue;
                m_DeploymentDatabase = DBSourceToolsLib.UserSettings.Instance().DatabaseProject.GetDatabaseEx(m_Name);
                //// deployment target

                this.TabText = m_DeploymentDatabase.NickName;
                this.m_PropertiesSplitContainer.Panel1Collapsed = false;
                this.m_toolStripButtonSave.Visible = false;
                this.m_PropertiesSplitContainer.Panel2Collapsed = true;

                dbPropUC = new DBSourceToolsLib.SysObjects.UI.Forms.DatabasePropertiesUC(m_DeploymentDatabase, false);
                dbPropUC.SetSourceDatabase(DBSourceToolsLib.UserSettings.Instance().DatabaseProject.SourceDatabases[0]);

                this.m_PropertiesSplitContainer.Panel1.Controls.Add(dbPropUC);

                m_TempOutputFileName = System.IO.Path.GetTempFileName();
                m_toolStripButtonForceDrop.Visible = true;
                toolStripButtonCreateZip.Visible = true;
            }

        }




        private void m_toolStripButtonDelete_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.m_IsDeploymentTarget)
                {
                    if (MessageBox.Show("Delete Deployment Target : " + m_DeploymentDatabase.NickName, "Delete", MessageBoxButtons.OKCancel)
                            == DialogResult.OK)
                    {
                        // TODO : COMPLETE 1.2.0.9 update DBExplorer treeview on delete.
                        SourceDatabase oSource = UserSettings.Instance().getSourceDatabase(m_Database.NickName);
                        oSource.RemoveTargetDatabase(m_DeploymentDatabase.NickName);
                        UserSettings.Instance().DatabaseProject.WriteProjectFile();

                        WindowList.Instance().RemoveWindow(m_DatabaseName,m_ObjectType,m_Name);

                        //this.m_Observer.NotifyEvent(m_DeploymentDatabase.NickName, null, null
                        //    , DBSourceToolsLib.Interfaces.SourceEditorEvent.TargetDeleted, null);
                        this.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm oError =
                new DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm(ex.ToString());
                            oError.ShowDialog(this);

            }
        }

        private void m_toolStripButtonDeployTarget_Click(object sender, EventArgs e)
        {
            try
            {
                string strMessage = "Are you sure you would like to deploy this target ?" + Environment.NewLine;
                strMessage += Environment.NewLine;
                strMessage += "NickName : " + this.m_DeploymentDatabase.NickName + Environment.NewLine;
                strMessage += "Database : " + this.m_DeploymentDatabase.DatabaseName + Environment.NewLine;
                strMessage += "Server   : " + this.m_DeploymentDatabase.DataSourceName + Environment.NewLine;
                strMessage += Environment.NewLine;
                strMessage += "Batch file : " + this.m_DeploymentDatabase.BaseDirectory + "\\Run_Create_Scripts.bat";
                strMessage += Environment.NewLine;

                if (MessageBox.Show(strMessage, "Deploy Target", MessageBoxButtons.OKCancel)
                    == DialogResult.OK)
                {

                    this.Cursor = Cursors.WaitCursor;

                    this.m_PropertiesSplitContainer.Panel2Collapsed = false;
                    //this.m_textBoxDeployResults.Text = "";
                    DateHelper oHelper = new DateHelper();


                    string strDate = String.Format("\\DeployResults_{0}_{1}.txt", oHelper.GetCurrentDateFormatted(),
                        oHelper.GetCurrentTimeFormatted());

                    string strOutputFileName = m_DeploymentDatabase.BaseDirectory + strDate;

                    DeployResultsForm oDeployForm = new DeployResultsForm(m_DeploymentDatabase.BaseDirectory + "\\Run_Create_Scripts.bat", strOutputFileName);
                    oDeployForm.ShowDialog(this);
                    this.Cursor = Cursors.Default;
                }
            }
            catch (Exception ex)
            {
                DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm oError =
                new DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm(ex.ToString());
                oError.ShowDialog(this);

            }

        }


        private void toolStripButtonSave_Click(object sender, EventArgs e)
        {
            this.dbPropUC.Save();
            //if (this.m_IsDeploymentTarget)
            //{
            //    this.m_DeploymentDatabase.CreateScript.ScriptText = this.m_codeEditCreate.Document.Text;

            //    this.m_DeploymentDatabase.CreateScript.WriteScript();

            //    this.m_DeploymentDatabase.DropScript.ScriptText = this.m_codeEditDrop.Document.Text;
            //    this.m_DeploymentDatabase.DropScript.WriteScript();
            //}
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            try
            {
                if (MessageBox.Show(this, "Are you sure you would like to Kill database " + m_DeploymentDatabase.DatabaseName
                    + " and close all current connections ", "Kill Database", MessageBoxButtons.OKCancel) == DialogResult.OK)
                {
                    Cursor = Cursors.WaitCursor;
                    try
                    {
                        m_DeploymentDatabase.ForceDrop();
                        MessageBox.Show("Kill database " + m_DeploymentDatabase.DatabaseName + " completed.");
                    }
                    catch (Exception ex)
                    {
                        DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm oError =
                            new DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm(ex.ToString());
                        oError.Show();

                        //MessageBox.Show(ex.ToString());
                    }
                    Cursor = Cursors.Default;
                }
            }
            catch (Exception ex)
            {
                DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm oError =
                new DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm(ex.ToString());
                oError.ShowDialog(this);

            }

        }

        private void toolStripButtonCreateZip_Click(object sender, EventArgs e)
        {
            if (m_saveFileDialog.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
            {
                try
                {
                    UserSettings.Instance().DatabaseProject.WriteProjectFile();

                    DBSourceToolsLib.SourceDatabaseWriter oWriter = new SourceDatabaseWriter(this,
                        DBSourceToolsLib.Commands.DatabaseCommandTypes.WriteToDisk,
                        UserSettings.Instance().DatabaseProject);

                    for (int i = 0; i < UserSettings.Instance().DatabaseProject.SourceDatabases.Count; i++)
                    {
                        SourceDatabase oSource = UserSettings.Instance().DatabaseProject.SourceDatabases[i];
                        oWriter.Execute(ref oSource, "isZip");
                        if (oWriter.HasErrors())
                            throw new Exception(oWriter.GetErrorMessage());
                    }


                    //CreateZipFile();
                    CreateDotNetZipFile(m_saveFileDialog.FileName);
                }
                catch (Exception ex)
                {
                    DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm oError =
                    new DBSourceToolsLib.SysObjects.UI.Forms.ErrorForm(ex.ToString());
                    oError.ShowDialog(this);

                }
            }

        }

        private void CreateDotNetZipFile(string strZipFileName)
        {
                DBSourceToolsLib.ZipWriter oZipWriter = new DBSourceToolsLib.ZipWriter(
                    m_saveFileDialog.FileName);

                oZipWriter.SetProjectFile(UserSettings.Instance().DatabaseProject.ProjectFileName);
                oZipWriter.SetDeploymentTargetNickName(m_DeploymentDatabase.NickName);
                oZipWriter.SetSourceDatabaseNickName(m_Database.NickName);

                oZipWriter.Execute(this);

                MessageBox.Show(strZipFileName + " created successfully");

        }

        #region older zip code
        //private void CreateZipFile()
        //{
        //    // TODO : COMPLETE 1.2.0.8 use sharpzip lib to create zip file. (albTotxo)
        //    byte[] emptyzip = new byte[]{80,75,5,6,0,0,0,0,0, 
        //          0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

        //    // ensure bin directory exists.
        //    DBSourceToolsLib.FileUtils oFileUtils = new FileUtils();
            
        //    string strSourceFolder = UserSettings.Instance().DatabaseProject.BaseDirectory + "\\" +
        //        UserSettings.Instance().CurrentDbNickName;
            
        //    string strTempPath = Path.GetTempPath();
        //    strTempPath += UserSettings.Instance().CurrentDbNickName;
        //    //string strTempZipFolder 
        //    oFileUtils.DeleteDirRecursive(strTempPath);

        //    // create Create_db.bat in root directory.
        //    oFileUtils.EnsureDirectoryExists(strTempPath); 
        //    string strRootBatchFile = strTempPath + "\\Create_" + this.m_DeploymentDatabase.NickName + ".bat";
        //    using (System.IO.StreamWriter sWriter = new System.IO.StreamWriter(strRootBatchFile))
        //    {
        //        sWriter.WriteLine("cd .\\DeploymentTargets\\" + m_DeploymentDatabase.NickName);
        //        sWriter.WriteLine("call Run_Create_Scripts.bat");
        //    }

        //    oFileUtils.EnsureDirectoryExists(strTempPath + "\\bin");
        //    Shell32.ShellClass scBinDir = new Shell32.ShellClass();
        //    Shell32.Folder sourceBinDir = scBinDir.NameSpace(UserSettings.Instance().StartupPath);
        //    Shell32.Folder targetBinDir = scBinDir.NameSpace(strTempPath + "\\bin");
        //    Shell32.FolderItems binItems = sourceBinDir.Items();
        //    targetBinDir.CopyHere(binItems, 10);

        //    //copy the xml project file with connection settings to an \\xml directory
        //    oFileUtils.EnsureDirectoryExists(strTempPath + "\\xml");
        //    string strProjectXmlFile = UserSettings.Instance().DatabaseProject.ProjectName + ".xml";
            
        //    // must build the database project again.

        //    System.IO.File.Copy(UserSettings.Instance().DatabaseProject.BaseDirectory + "\\" +
        //        strProjectXmlFile, strTempPath + "\\xml\\" + strProjectXmlFile, true);

        //    oFileUtils.CopyFilesRecursive(strSourceFolder, strTempPath);

        //    Shell32.ShellClass sc = new Shell32.ShellClass();
        //    Shell32.Folder SrcFlder = sc.NameSpace(strTempPath);
        //    Shell32.FolderItems items = SrcFlder.Items();

        //    // pickup project xml file.
        //    string strXmlFile = UserSettings.Instance().DatabaseProject.BaseDirectory + "\\";

        //    string strZipFileName = strSourceFolder + ".zip";
        //    FileStream fs = File.Create(strZipFileName);
        //    fs.Write(emptyzip, 0, emptyzip.Length);
        //    fs.Flush();
        //    fs.Close();
        //    fs = null;
        //    Shell32.Folder DestFlder = sc.NameSpace(strZipFileName);
        //    DestFlder.CopyHere(items, 20);

        //    System.Threading.Thread.Sleep(1000);

        //    MessageBox.Show(strZipFileName + " created successfully");
        //}
        #endregion


    }
}
